// Copyright 2014 Square Inc.
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//        http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.

$(document).ready(function() {
  new PageManager().setup();
});

function PageManager() {
  this.setup = function() {
    this.setupWatchedBugsTable();
    this.setupAssignedBugsTable();
    this.setupMyFeed();
    this.setupFindAnyProject();
  };

  this.setupFindAnyProject = function() {
    new DynamicSearchField($('#find-project'), this.processAnyProjectSearchResults);
    this.processAnyProjectSearchResults(''); // pre-populate with most recent projects
  };

  this.processAnyProjectSearchResults = function(query) {
    var self = this;
    $.ajax('<%= projects_url(format: 'json') %>?query=' + encodeURIComponent(query), {
      type:    'GET',
      success: function(results) {
        var resultList = $('#find-project-search-results');
        resultList.find('li').remove();
        $.each(results, function(_, project) {
          var li = $('<li/>').appendTo(resultList);
          var h5 = $('<h5/>').append($('<a/>').text(project.name).attr('href', project.url)).appendTo(li);

          if (project.role == null) {
            var btn = $("<button/>").text("Join").appendTo(h5);
            btn.click(function() {
              $.ajax(project.join_url, {
                type: 'POST',
                success: function() { self.processAnyProjectSearchResults(query); },
                error: function() { new Flash('alert').text("Couldn’t join project."); }
              });
            });
          }

          var p = $('<p/>').appendTo(li);
          switch (project.role) {
            case 'owner':
              $('<strong/>').text('Owner').appendTo(p);
              break;
            case 'admin':
              $('<strong/>').text('Administrator').appendTo(p);
              break;
            case 'member':
              $('<strong/>').text('Project member').appendTo(p);
              break;
            default:
              p.text("Owned by ");
              $('<a/>').text(project.owner.name).attr('href', project.owner.url).appendTo(p);
          }
          p.append(' — created ');
          $('<time/>').attr('datetime', project.created_at).appendTo(p).liveUpdate();
        });
      },
      error:   function() { new Flash('alert').text("Error retrieving search results."); }
    });
  };

  this.setupWatchedBugsTable = function() {
    var table = new SortableTable($('#watched-bugs'),
      "<%= account_bugs_url(format: 'json', type: 'watched') %>",
      [
        { key: 'project_and_environment', title: "Project", sortable: false, htmlGenerator: function(bug) {
          var span = $('<span/>').text(bug.environment.name);
          $('<br/>').prependTo(span);
          $('<strong/>').text(bug.project.name).prependTo(span);
          return span;
        } },
          { key: 'class_message', title: "Message", sortable: false, htmlGenerator: function(bug) {
            var sp = $('<span/>').addClass('long-words').text(bug.message_template);
            $('<br/>').prependTo(sp);
            $('<tt/>').text(bug.class_name).prependTo(sp);
            return sp;
          } },
        { title: "File", sortable: false, textGenerator: formatBugFile },
        { key: 'occurrences', title: "Counts", sortable: false, htmlGenerator: function(bug) {
          var sp = $('<span/>');
          sp.append(bug.occurrences_count);
          $('<i/>').addClass('fa fa-exclamation-circle').appendTo(sp);
          if (bug.comments_count > 0) {
            sp.append(' ' + bug.comments_count);
            $('<i/>').addClass('fa fa-comment').appendTo(sp);
          }
          return sp;
        } },
        { key: 'latest', title: "Latest", sortable: false, htmlGenerator: function(bug) {
          return $('<time/>').attr('datetime', bug.latest_occurrence).liveUpdate();
        } },
        { key: 'user_name', title: "Assigned To", sortable: false, textGenerator: function(bug) { return bug.assigned_user ? bug.assigned_user.name : "no one"; } },
        { key: 'unwatch', title: '', sortable: false, htmlGenerator: function(bug) {
          return $('<a/>').addClass('fa fa-star icon-large unwatch').attr('href', '#').click(function() {
            $.ajax(bug.watch_url, {
              type: 'POST',
              success: function() { table.refreshData(); },
              error: function() {
                new Flash('alert').text("Couldn’t unwatch that bug.");
                table.refreshData();
              },
              dataType: 'text'
            });
            return false;
          });
        } }
      ],
      {
        sort_key:    'latest',
        scroll_with: 'id'
      }
    ).refreshData();
  };

  this.setupAssignedBugsTable = function() {
      new SortableTable($('#assigned-bugs'),
                        "<%= account_bugs_url(format: 'json') %>",
                        [
                          { key: 'project_and_environment', title: "Project", sortable: false, htmlGenerator: function(bug) {
                            var span = $('<span/>').text(bug.environment.name);
                            $('<br/>').prependTo(span);
                            $('<strong/>').text(bug.project.name).prependTo(span);
                            return span;
                          } },
                          { key: 'class_message', title: "Message", sortable: false, htmlGenerator: function(bug) {
                            var sp = $('<span/>').addClass('long-words').text(bug.message_template);
                            $('<br/>').prependTo(sp);
                            $('<tt/>').text(bug.class_name).prependTo(sp);
                            return sp;
                          } },
                          { title: "File", sortable: false, textGenerator: formatBugFile },
                          { key: 'occurrences', title: "Counts", sortable: false, htmlGenerator: function(bug) {
                            var sp = $('<span/>');
                            sp.append(bug.occurrences_count);
                            $('<i/>').addClass('fa fa-exclamation-circle').appendTo(sp);
                            if (bug.comments_count > 0) {
                              sp.append(' ' + bug.comments_count);
                              $('<i/>').addClass('fa fa-comment').appendTo(sp);
                            }
                            return sp;
                          } },
                          { key: 'latest', title: "Latest", sortable: false, htmlGenerator: function(bug) {
                            return $('<time/>').attr('datetime', bug.latest_occurrence).liveUpdate();
                          } },
                          { key: 'status', title: "Status", sortable: false, textGenerator: function(bug) {
                            switch (bug.status) {
                              case 'open': case 'assigned': return "unresolved";
                              case 'fixed': return "fixed";
                              case 'fix_deployed': return "fix deployed";
                            }
                          } }
                        ],
                        {
                          sort_key:    'latest',
                          scroll_with: 'id'
                        }
      ).refreshData();
    };

  this.setupMyFeed = function() {
    new Feed("<%= account_events_url(format: 'json') %>", $('#events'), {bugHeader: true});
  };
}
